﻿// /*------------------------------------------------------------
// 工程名:    Ensemble
// 文件名:    PluginManager.cs
// 编写人:    yhh
// 编写日期: 下午 5:41
// -------------------------------------------------------------*/

using System;
using System.Collections.Generic;

namespace Ensemble
{
    public abstract class PluginManager<T> where T : EnsemblePlugin
    {
        public event EventHandler<EnsemblePluginEventArgs> PluginsReady = null;
        private Dictionary<string, T> pluginRegistry = new Dictionary<string, T>();
        private IPluginLoader pluginLoader = null;

        public IPluginLoader PluginLoader {
            get { return pluginLoader; }
        }

        public IEnumerable<T> LoadedPlugins
        {
            get { return this.pluginRegistry.Values; }
        }

        public void Init(IPluginLoader pluginLoader)
        {
            if(pluginLoader != null)    throw new InvalidOperationException("插件管理已经初始化");

            this.pluginLoader = pluginLoader;
            this.pluginLoader.AssemblyResolve += pluginLoader_AssemblyResolve;
        }

        private void pluginLoader_AssemblyResolve(object sender, AssemblyResolveEventArgs args)
        {
            if (args.IsResolved)    return;

            T plugin;
            if (pluginRegistry.TryGetValue(args.AssemblyName,out plugin))
            {
                args.Resolve(plugin.PluginAssembly);
                return;
            }
        }
    }
}